<template>
  <basic-container>
    <avue-crud :option="option" :table-loading="loading" :data="data" :page.sync="page" :permission="permissionList"
      :before-open="beforeOpen" v-model="form" ref="crud" @row-update="rowUpdate" @row-save="rowSave" @row-del="rowDel"
      @search-change="searchChange" @search-reset="searchReset" @selection-change="selectionChange"
      @current-change="currentChange" @size-change="sizeChange" @refresh-change="refreshChange" @on-load="onLoad">
      <template slot-scope="scope" slot="menuLeft">
        <el-button type="primary" icon="el-icon-plus" size="small" @click="rowAdd()">新增</el-button>
      </template>
      <!-- 自定义操作列 -->
      <template #menu="{ row, index, size }">
        <el-button type="primary" :size="'mini'" icon="el-icon-view" @click="rowView(row, index)" style="width: 23px;
        height: 22px; padding: 0;"></el-button>
        <el-button type="primary" :size="'mini'" icon="el-icon-edit" @click="rowEdit(row, index)" style="width: 23px;
        height: 22px; padding: 0;"></el-button>
        <el-button type="danger" :size="'mini'" icon="el-icon-delete" @click="rowDel(row, index)" style="width: 23px;
        height: 22px; padding: 0;"></el-button>
      </template>
      <!-- 单元格 -->
      <template slot-scope="{ row }" slot="status">
        <el-switch v-model="row.status" :active-value="0" :inactive-value="1" active-color="#409EFF"
          inactive-color="#d2d6de" active-text="上架" inactive-text="下架" @change="changeState(row)">
        </el-switch>
      </template>
      <!-- <template slot-scope="{ row }" slot="status">
        <p v-if="row.status == 0" class="normal">正常</p>
        <p v-else-if="row.status == 1" class="un-normal">禁用</p>
      </template> -->
    </avue-crud>
  </basic-container>
</template>

<script>
import { getProductCategoryList } from '../productCategory/api/productCategory'
import { getAllBrandList } from '../brand/api/brand'
import { getProductList, updateProductItem, delProductItem, setProductItemStatus, getProductSkuInfo } from "./api/product";
import { mapGetters } from "vuex";
import productEdit from './components/ProductEdit.vue'
export default {
  components: {
    productEdit
  },
  data() {
    return {
      form: {},
      query: {},
      loading: true,
      page: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
      selectionList: [],
      option: {
        menuType: 'button',
        height: "auto",
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: false,

        index: true,
        indexLabel: '序号',
        searchBtnText: '提交',
        searchBtnIcon: '提交',
        emptyBtnText: '重置',
        emptyBtnIcon: '重置',
        viewBtn: false,
        addBtn: false,
        addBtnText: '添加',
        addBtnIcon: 'el-icon-plus',
        editBtn: false,
        editBtnText: '',
        selection: false,
        dialogClickModal: false,
        delBtn: false,
        delBtnText: '',
        labelWidth: 110,
        searchLabelWidth: 100,
        column: [
          {
            label: "商品名称 ",
            prop: "name",
            search: true,
            rules: [{
              required: true,
              message: "请输入商品名称 ",
              trigger: "blur"
            }],
          },
          {
            label: "品牌",
            prop: "brand_id",
            type: 'select',
            search: true,
            dicData: [],
            props: {
              value: "id",
              label: "name",
            },
            rules: [{
              required: true,
              message: "请选择品牌",
              trigger: "change"
            }],
          },
          {
            label: "分类",
            prop: "category_id",
            type: 'tree',
            search: true,
            dicData: [],
            props: {
              value: "id",
              label: "name",
            },
            rules: [{
              required: true,
              message: "请选择分类",
              trigger: "change"
            }],
          },
          {
            label: "商品单位",
            prop: "unit",
          },
          {
            label: '封面图片',
            prop: 'cover_picture',
            dataType: 'array',
            type: 'upload',
            propsHttp: {
              url: 'file',
              home: $imgBaseUrl
            },
            span: 24,
            listType: 'picture-card',
            accept: [".png", ".jpg", ".jpeg"],
            tip: '上传png、jpg、jpeg的图片',
            action: '/admin/common/upload',
            uploadAfter: (file, done) => {
              console.log(file, '封面图片file',);
              done();
            },
            rules: [{
              required: true,
              message: "请选择封面图片",
              trigger: "change"
            }],
          },
          {
            label: '相册图片',
            prop: 'album',
            dataType: 'array',
            type: 'upload',
            propsHttp: {
              url: 'file',
              home: $imgBaseUrl
            },
            span: 24,
            listType: 'picture-card',
            accept: [".png", ".jpg", ".jpeg"],
            tip: '上传png、jpg、jpeg的图片',
            action: '/admin/common/upload',
            uploadAfter: (file, done) => {
              console.log(file, '相册图片file', this.form);
              this.form.album = file;
              done();
            },
            rules: [{
              required: true,
              message: "请选择相册图片",
              trigger: "change"
            }],
          },
          {
            label: '视频',
            prop: 'video',
            dataType: 'array',
            type: 'upload',
            propsHttp: {
              url: 'file',
              home: $imgBaseUrl
            },
            listType: 'picture-card',
            span: 24,
            tip: '上传视频',
            action: '/admin/common/upload',
            uploadAfter: (file, done) => {
              console.log(file, '视频file',);
              done();
            }
          },
          {
            label: "商品详情",
            prop: "detail",
            rules: [{
              required: true,
              message: "请输入商品详情",
              trigger: "blur"
            }],
          },
          {
            label: "基础价格",
            prop: "base_price",
            rules: [{
              required: true,
              message: "请输入基础价格",
              trigger: "blur"
            }],
          },
          {
            label: "会员基础价格",
            prop: "member_base_price",
            rules: [{
              required: true,
              message: "请输入会员基础价格",
              trigger: "blur"
            }],
          },
          {
            label: "状态",
            prop: "status",
            search: true,
            type: 'select',
            dicData: [{
              label: '上架',
              value: 0
            }, {
              label: '下架',
              value: 1
            }],
            rules: [{
              required: true,
              message: "请选择状态",
              trigger: "blur"
            }],
          },

        ],
      },
      data: [],

    };
  },
  computed: {
    ...mapGetters(["permission"]),

    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.user_add, true),
        viewBtn: this.vaildData(this.permission.user_view, true),
        delBtn: this.vaildData(this.permission.user_delete, true),
        editBtn: this.vaildData(this.permission.user_edit, true),
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  mounted() {
    this.initAllBrandData();
    this.initProductCategoryData();
  },
  methods: {
    submitEdit() {
      const skuData = this.$refs.productEditor.submitForm()
      updateProductItem(skuData).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );

    },
    // 获取商品分类
    initProductCategoryData() {
      getProductCategoryList({ type: 1 }).then(
        (res) => {
          this.option.column[2].dicData = res.data
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    // 获取所有品牌
    initAllBrandData() {
      getAllBrandList({}).then(
        (res) => {
          this.option.column[1].dicData = res.data
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    // 改变状态
    changeState(data) {
      const params = {
        id: data.id,
        status: data.status
      };
      setProductItemStatus(params).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowAdd() {
      this.$router.push({
        path: "/product/update",
      });
      this.form = {}
    },
    rowView(row, index) {
      this.form = { ...row }
      this.$router.push({
        path: "/product/update",
        query: {
          queryId: row.id,
          type: 'view'
        }
      });
    },
    rowEdit(row, index) {
      this.$router.push({
        path: "/product/update",
        query: {
          queryId: row.id,
          type: 'update'
        }
      });

    },
    rowDel(row, index) {
      this.$refs.crud.rowDel(row, index);
    },
    rowSave(row, done, loading) {
      return
      const data = row;
      data.cover_picture = row.cover_picture_full
      data.spec_info = row.spec_info.map(item => {
        return {
          spec_name: item.spec_name,
          spec_value: item.spec_value
        }
      })
      data.sku_info = row.sku_info.map(item => {
        return {
          buy_price: item.buy_price,
          member_price: item.member_price,
          picture: item.picture,
          price: item.price,
          sku_code: item.sku_code,
          spec_info: item.spec_info.map(j => {
            return {
              spec_name: j.spec_name,
              spec_value: j.spec_value
            }
          }),
          status: item.status,
          stock: item.stock,
          trade_price: item.trade_price,
        }
      })

      updateProductItem(data).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        }
      );
    },
    rowUpdate(row, index, done, loading) {
      const data = row;
      console.log(120, row);
      updateProductItem(data).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          done();
        },
        (error) => {
          window.console.log(error);
          loading();
        }
      );
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", '提示', {
        cancelButtonText: "取消",
        confirmButtonText: "确定",
        type: "warning",
      })
        .then(() => {
          return delProductItem({ id: row.id });
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
        });
    },

    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!",
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen(done, type) {
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, search = {}) {
      this.loading = true;
      let param = {
        page: page.currentPage,
        size: page.pageSize,
      }
      getProductList({ ...param, ...search }).then((res) => {
        const resData = res.data;
        this.page.total = resData.total;
        this.data = resData.list;
        this.loading = false;
        this.selectionClear();
      });
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
  },
};
</script>

<style>
.el-switch__label * {
  line-height: 1;
  font-size: 12px;
  display: inline-block;
}

.el-switch__label {
  position: absolute;
  display: none;
  color: #fff !important;
  font-size: 12px !important;
}

/*打开时文字位置设置*/
.el-switch__label--right {
  z-index: 1;
  right: -6px;
}

/*关闭时文字位置设置*/
.el-switch__label--left {
  z-index: 1;
  left: 22px;
}

/*显示文字*/
.el-switch__label.is-active {
  display: block;
}

/*开关宽度*/
.el-switch .el-switch__core,
.el-switch .el-switch__label {
  width: 50px !important;
}
</style>
<style lang="scss" scoped>
// ::v-deep .el-table thead th .cell {
//   border-left: none;
// }

.normal {
  color: #409EFF;
  display: inline-block;
  display: flex;
  align-items: center;

  &::before {
    content: '';
    display: inline-block;
    width: 10px;
    height: 10px;
    border-radius: 10px;
    /**控制形状**/
    background-color: #409EFF;
    /**控制图标颜色**/
    margin-right: 4px
      /**图标与文字距离**/
  }
}

.un-normal {
  color: #d2d6de;
  display: inline-block;

  &::before {
    content: '';
    display: inline-block;
    width: 10px;
    height: 10px;
    border-radius: 10px;
    /**控制形状**/
    background-color: #d2d6de;
    /**控制图标颜色**/
    margin-right: 4px
      /**图标与文字距离**/
  }
}
</style>
